/**
 * 维护视频号库（用于聊天时发送）
 */
import { getLogger, Service } from '@gnlab/utils'
import { MemSubject } from '@gnlab/utils/rx'
import type { Services } from '@/services'
import { API } from '@/services/common/api'
import { type VideonumWord } from '@/services/common/definition'

const logger = getLogger('services/resources/videonums')

export type Videonum = Omit<VideonumWord, 'type'>

// 已保存到“视频号库”里的消息，会额外获得 id 并指定类型
export interface SavedVideonum extends Videonum {
  id: number
  type: VideonumType // 0: 全员视频号    1: 我的视频号
}

export enum VideonumType {
  Global = 0, // 全员消息
  Personal = 1, // 个人消息
}

export class Videonums extends Service<Services> {
  private get auth() {
    return this.services.auth
  }

  registered() {
    void this.auth.accountId.then(() => {
      void this.load()
    })
  }

  private readonly _list = new MemSubject<SavedVideonum[]>([])
  list = this._list.asStream()

  async load() {
    const resp = await API<SavedVideonum[]>('/VideoNum/GetVideoNums')
    if (resp.success) {
      this._list.next(resp.data)
    } else {
      logger.warn('视频号列表加载失败', resp.error)
    }
  }

  async add(type: VideonumType, videonum: Videonum) {
    const resp = await API('/VideoNum/AddVideoNum', { data: { ...videonum, type }, formatter() {} })
    if (resp.success) {
      void this.load()
    } else {
      const typeName = type === VideonumType.Global ? '全员' : '个人'
      logger.warn(`${typeName}视频号添加失败：${resp.error}`)
    }
    return resp
  }

  async remove(id: number) {
    const resp = await API('/VideoNum/RemoveVideoNum', { data: { id }, formatter() {} })
    if (resp.success) void this.load()
    else logger.warn(`视频号删除失败：${resp.error}`)
    return resp
  }
}
